<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="出库单" prop="shipmentOrderId">
          <el-input v-model="queryParams.shipmentOrderNo" placeholder="请输入出库单" disabled />
        </el-form-item>
        <el-form-item label="出库类型" prop="shipmentOrderType">
          <el-radio-group v-model="queryParams.shipmentOrderType" size="large"
            :disabled="shipmentOrderNo !== undefined">
            <el-radio-button v-for="dict in shipment_order_type" :label="dict.value">
              {{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select @click="user" v-model="queryParams.customerId" placeholder="请选择客户"
            :disabled="shipmentOrderNo !== undefined">
            <el-option v-for="dict in userList" :key="'key-' + dict.customerNo" :label="dict.customerName"
              :value="dict.customerNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库订单" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入出库订单" clearable
            :disabled="shipmentOrderNo !== undefined" />
        </el-form-item>
        <el-form-item label="备注" prop="orderNo">
          <el-input type="textarea" v-model="queryParams.remark" placeholder="备注...100个字符以内" rows="4" maxlength="100"
            style="width: 1000px;" show-word-limit="show-word-limit" resize="none" clearable />
        </el-form-item>
        <el-form-item label="总金额">
          <el-input-number v-model="queryParams.receivableAmount" :precision="2" :step="0.1" :min="0" readonly />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 15px;">
      <b style="font-size: larger;">物料明细</b>
      <el-button type="success" style="margin-left: 10px;" plain @click="ddd = true"
        :disabled="multiple">批量选择仓库</el-button>
      <el-button type="primary" plain icon="Plus" style="margin-left: 800px; margin-bottom: 10px;"
        @click="handleAdd">添加物料</el-button>
      <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="select"/>
        <el-table-column label="物料名" align="center" prop="itemName" />
        <el-table-column label="物料编号" align="center" prop="itemNo" />
        <el-table-column label="计划数量" align="center" prop="planQuantity" width="220px">
          <template #default="scope">
            <el-input-number v-model="scope.row.planQuantity" :min="1"
              :disabled="scope.row.shipmentOrderStatus == 4 || scope.row.shipmentOrderStatus == 3" />
          </template>
        </el-table-column>
        <el-table-column label="仓库" align="center" width="200" prop="warehouseId">
          <template #default="scope">
            <el-select @click="selectware" v-model="scope.row.warehouseId" placeholder="请选择仓库"
              :disabled="scope.row.shipmentOrderStatus == 4 || scope.row.shipmentOrderStatus == 3">
              <el-option v-for="dict in options" :key="'key-' + dict.warehouseId" :label="dict.warehouseName"
                :value="dict.warehouseId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库区" align="center" width="200" prop="areaId">
          <template #default="scope">
            <el-select @click="Dataseachware(scope.row.warehouseId)" v-model="scope.row.areaId" placeholder="请选择库区"
              :disabled="scope.row.shipmentOrderStatus == 4 || scope.row.shipmentOrderStatus == 3">
              <el-option v-for="dict in ItemAreas" :key="'key-' + dict.areaNo" :label="dict.areaName"
                :value="dict.areaNo" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="unitPrice">
          <template #default="scope">
              {{ scope.row.planQuantity * scope.row.unitPrice }} 元
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['wms:detail:remove']"
              :disabled="scope.row.shipmentOrderStatus == 4 || scope.row.shipmentOrderStatus == 3">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer" align="center" style="margin-top: 10px;">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-card>

    <!-- 添加或修改出库单详情对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form :model="form" label-width="80px" :inline="true" v-show="showSearch">
        <el-form-item label="物料类型">
          <el-tree-select v-model="form.shipmentOrderId" :data="optionsa" :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="快速筛选">
          <el-input v-model="form.itemName" placeholder="名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="onClick">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="orderdetaillist" @selection-change="handleSelectionChange"
        ref="multipleTableRef">
        <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
        <el-table-column label="物料名称" align="center" prop="itemName" />
        <el-table-column label="物料编号" align="center" prop="itemNo" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量选择仓库 -->
    <el-dialog title="选择仓库与库区" v-model="ddd" width="700px" append-to-body>
      <el-form :inline="true">
        <el-form-item label="仓库">
          <el-select @click="selectware" v-model="warehouse" placeholder="请选择仓库">
            <el-option @click="Dataseachware(dict.warehouseId)" v-for="dict in options" :key="'key-' + dict.warehouseId"
              :label="dict.warehouseName" :value="dict.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="库区">
          <el-select v-model="area" placeholder="请选择库区">
            <el-option v-for="dict in ItemAreas" :key="'key-' + dict.areaNo" :label="dict.areaName"
              :value="dict.areaNo" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addWarehouse">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orderdetail">
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/wms/orderdetail";
import { listItem } from "@/api/wms/item";
import { listWarehouse } from "@/api/wms/warehouse";
import { selectList } from "@/api/wms/area";
import { listCustomer } from "@/api/wms/customer";
import { addOrder, getOrder, updateOrder } from "@/api/wms/orders";
import { computed } from "vue";
const { proxy } = getCurrentInstance();
const { shipment_order_type } = proxy.useDict('shipment_order_type');

const detailList = ref([]);
const userList = ref([]);
const orderdetaillist = ref([]);
const open = ref(false);
const ddd = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const row = ref();
const options = ref([]);//仓库
const warehouse = ref();
const ItemAreas = ref([]);//库区
const area = ref();
const multipleTableRef = ref();
const shipmentOrderNo = proxy.$route.query.shipmentOrderNo //页面传过来的出库单
const selectable = (row) => {
  if (detailList.value.length === 0) {
    return true;
  } else {
    return !detailList.value.some(item => row.itemNo === item.itemNo);
  }
};
const select = (row) => {
  if (row.shipmentOrderStatus == 4 || row.shipmentOrderStatus == 3) {
    return false;
  } else {
    return true;
  }
};
//计算总金额
// function sum(){
//   let s = 0;
//   detailList.value.forEach(item=>{
//     s += item.planQuantity * item.unitPrice;
//   })
//   queryParams.value.money = s;
// }
//选择物料类型时的测试死数据
const optionsa = ref([
  {
    label: '电子产品',
    value: 1,
    children: [
      {
        label: '手机',
        value: 101,
        children: [
          {
            label: '苹果',
            value: 10101,
          }, {
            label: '安卓',
            value: 10102,
          }
        ]
      },
      {
        label: '打印机',
        value: 102,
        disabled: true,
      }
    ]
  },
  {
    label: '大电器',
    value: 2,
    children: [
      {
        label: '冰箱',
        value: 201,
      },
      {
        label: "空调",
        value: 202,
      },
      {
        label: '电视机',
        value: 203
      }
    ]
  }
])

function nowDate() {
  var getTime = new Date().getTime(); //获取到当前时间戳
  var time = new Date(getTime); //创建一个日期对象
  var year = time.getFullYear(); // 年
  var month = (time.getMonth() + 1).toString().padStart(2, '0'); // 月
  var date = time.getDate().toString().padStart(2, '0'); // 日
  var hour = time.getHours().toString().padStart(2, '0'); // 时
  var minute = time.getMinutes().toString().padStart(2, '0'); // 分
  var second = time.getSeconds().toString().padStart(2, '0'); // 秒
  return (
    'CK-' + year + "-" + month + "-" + date + "-" + hour + "" + minute + "" + second
  )
}
//初始化
function user() {
  listCustomer().then(response => {
    userList.value = response.rows;
  })
}
function close() {
  const obj = { path: "/orders" };
  proxy?.$tab.closeOpenPage(obj);
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shipmentOrderNo: shipmentOrderNo !== undefined ? shipmentOrderNo : nowDate(),//当页面传值过来证明是修改
    shipmentOrderType: null,
    customerId: null,
    orderNo: null,
    remark: null,
    receivableAmount: computed(() => {
      let sum = 0;
      detailList.value.forEach(item => {
        sum += item.planQuantity * item.unitPrice;
      })
      return sum;
    }),
  },
  rules: {
    delFlag: [
      { required: true, message: "删除标识不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

//查询物料
function onClick() {
  // console.log(form.value);
  listItem(form.value).then(response => {
    // console.log(response)
    orderdetaillist.value = response.rows;
    total.value = response.total;
  })
}

//初始化仓库下拉框
function selectware() {
  listWarehouse().then(response => {
    options.value = response.rows;
  })
}

//根据仓库id查询库区
function Dataseachware(id) {
  console.log(id)
  selectList(id).then(response => {
    ItemAreas.value = response.rows;
  })
}

//批量选择仓库库区
function addWarehouse() {
  detailList.value.forEach(item => {
    row.value.forEach(it => {
      if (item.id === it.id) {
        item.warehouseId = warehouse.value;
        item.areaId = area.value;
      }
    })
  })
  cancel();
}



selectware();//初始化仓库下拉框
user();//初始化客户下拉框
/** 查询出库单详情列表 */
function getList() {
  //是修改则查询数据，不是修改则不查询
  if (shipmentOrderNo !== undefined) {
    readonly.value = 'readonly'; // 如果是修改就禁止修改上半部分的数据
    //查询上半部分的数据
    getOrder(shipmentOrderNo).then(response => {
      // 查询成功后将值赋给对应变量
      queryParams.value.shipmentOrderType = response.data.shipmentOrderType;
      queryParams.value.customerId = response.data.customerId + ""; //传过来的客户编号下拉框值为number需要转换为String才能正常显示出来
      queryParams.value.orderNo = response.data.orderNo;
      queryParams.value.remark = response.data.remark;
    })
    loading.value = true;
    //根据入库单号查询物料
    listDetail({ shipmentOrderId: shipmentOrderNo.replaceAll("-", "").slice(2) }).then(response => {
      detailList.value = response.rows;
      detailList.value.forEach(item => {
        item.warehouseId = item.warehouseId + "";//传过来的仓库编号下拉框值为number需要转换为String才能正常显示出来
        item.areaId = item.areaId + "";//传过来的库区编号下拉框值为number需要转换为String才能正常显示出来
        Dataseachware(item.warehouseId);//初始化库区
      })
      // console.log(detailList.value);
      total.value = response.total;
      loading.value = false;
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  ddd.value = false;
  reset();
}

// 表单重置
function reset() {
  options.value = [];
  warehouse.value = null;
  ItemAreas.value = [];
  area.value = null;
  form.value = {
    id: null,
    shipmentOrderId: null,
    itemName: null,
    itemId: null,
    planQuantity: null,
    realQuantity: null,
    rackId: null,
    money: null,
    delFlag: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    warehouseId: null,
    areaId: null,
    shipmentOrderStatus: null
  };
  proxy.resetForm("detailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  row.value = selection;
}

/** 新增按钮操作 */
function handleAdd() {
  listItem(form.value).then(response => {
    orderdetaillist.value = response.rows;
    total.value = response.total;
  })
  reset();
  open.value = true;
  title.value = "添加物料";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDetail(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改出库单详情";
  });
}

/** 提交按钮 */
function submitForm() {
  // console.log(row.value)
  row.value.forEach(item => {
    item.planQuantity = 1;
    item.warehouseId = '';
    item.areaId = '';
    detailList.value.push(item);
  });
  open.value = false;
  // console.log(detailList.value)
  multipleTableRef.value.clearSelection();
  // proxy.$refs["detailRef"].validate(valid => {
  //   if (valid) {
  //     if (form.value.id != null) {
  //       updateDetail(form.value).then(response => {
  //         proxy.$modal.msgSuccess("修改成功");
  //         open.value = false;
  //         getList();
  //       });
  //     } else {
  //       addDetail(form.value).then(response => {
  //         proxy.$modal.msgSuccess("新增成功");
  //         open.value = false;
  //         getList();
  //       });
  //     }
  //   }
  // });
}

/** 删除按钮操作 */
function handleDelete(row) {
  detailList.value = detailList.value.filter(item => {
    return item.itemNo !== row.itemNo;
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/detail/export', {
    ...queryParams.value
  }, `detail_${new Date().getTime()}.xlsx`)
}

//添加出库单
function submit() {
  detailList.value.forEach(item => {
    item.itemId = item.itemNo;
    item.money = item.planQuantity * item.unitPrice;
  })
  queryParams.value.details = detailList.value;
  console.log(queryParams.value);
  if (shipmentOrderNo !== undefined) {
    updateOrder(queryParams.value).then(response => {
      proxy.$modal.msgSuccess("操作成功");
      const obj = { path: "/orders" };
      proxy?.$tab.closeOpenPage(obj);
    })
  } else {
    addOrder(queryParams.value).then(response => {
      proxy.$modal.msgSuccess("操作成功");
      const obj = { path: "/orders" };
      proxy?.$tab.closeOpenPage(obj);
    })
  }
}

getList();
</script>
